package com.mall.server.controller;

import com.mall.server.model.dto.*;
import com.mall.server.service.UserService;
import com.mall.server.service.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@RestController
@RequestMapping("/api/auth")
public class AuthController {
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private VerificationCodeService verificationCodeService;
    
    @PostMapping("/login")
    public ResponseEntity<ApiResponse<TokenResponse>> login(@Valid @RequestBody LoginRequest loginRequest) {
        try {
            TokenResponse tokenResponse = userService.login(loginRequest);
            return ResponseEntity.ok(ApiResponse.success(tokenResponse));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.<TokenResponse>error(400, e.getMessage()));
        }
    }
    
    @PostMapping("/login/code")
    public ResponseEntity<ApiResponse<TokenResponse>> loginWithCode(@Valid @RequestBody VerifyCodeLoginRequest request) {
        try {
            TokenResponse tokenResponse = userService.loginWithVerifyCode(request);
            return ResponseEntity.ok(ApiResponse.success(tokenResponse));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.<TokenResponse>error(400, e.getMessage()));
        }
    }
    
    @PostMapping("/code/send")
    public ResponseEntity<ApiResponse<String>> sendCode(@Valid @RequestBody SendCodeRequest request) {
        try {
            String code = verificationCodeService.generateCode(request.getPhone());
            return ResponseEntity.ok(ApiResponse.success("验证码发送成功", code));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(ApiResponse.<String>error(400, e.getMessage()));
        }
    }
} 